<template>
  <!-- 台账统计汇总 -->
  <a-collapse v-model="activeKey" :bordered="false" expand-icon-position="right" class="mb12">
    <a-collapse-panel style="background: #e6f3fc; border: none" :show-arrow="false">
      <template slot="header">
        <a-row type="flex" justify="space-between" align="middle" style="width: 100%">
          <div>
            {{ title || $route.meta.title }} 
            <!-- 遍历汇总集合 -->
            <span v-for="(item, index) in countList" :key="index"
              >{{ item.title }}
              <a v-if="item.value=='total'"><b>{{ countInfo[item.value] || 0 }}</b></a>
              <a v-else><b>{{selectLength || 0 }}</b></a>{{ !item.needUnit ? '' : item.unit || '个' }}{{ index != countList.length - 1 ? '，' : '' }}</span
            >
          </div>
          <div>
            <a class="btn_right">
              <span>{{ activeKey.length > 0 ? '收起' : '展开' }}详细汇总信息</span>
              <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
            </a>
          </div>
        </a-row>
      </template>
      <div>
        <div class="about-master-container">
          <a-form-model ref="form" :model="queryParam">
            <a-row>
              <a-col span="8">
                <a-form-model-item label="排名逻辑" class="requiredFormItem">
                  <a-select v-model="queryParam.rankingLogic" placeholder="请选择" @change="refresh">
                    <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.key">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="时间选择" class="requiredFormItem">
                  <a-range-picker v-model="queryParam.searchTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-button type="primary" style="margin-left: 20px" @click="search"> 确定 </a-button> 
                <a-button type="primary" style="margin-left: 20px" v-btn-permission="'stm_013_exp_05'" :loading="expLoading" @click="achievementsLedgerExportFc"> 导出 </a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <a-tabs :active-key="countTableType" @change="switchSummary">
          <a-tab-pane :key="0" tab="分公司排名" />
          <a-tab-pane :key="1" tab="项目排名" />
          <!-- <a-tab-pane
            :key="3"
            tab="完成人排名"
          /> -->
        </a-tabs>
        <a-card>
          <b-table class="summary-table" ref="tableSummary" :show-page="false" :columns="columnsTotal" :request="loadDataSummary" />
        </a-card>
      </div>
    </a-collapse-panel>
  </a-collapse>
</template> 

<script>
import { Collapse } from 'ant-design-vue'
import {  achievementsLedgerExport } from '@/api/achievementsManage'

export default {
  name: 'AuditSummary',
  components: {
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel']
  },
  props: {
    // 标题
    title: {
      type: String,
      default: () => ''
    },
    selectLength:{
      type: Number,
      default: () => 0
    },
    countList: {
      type: Array,
      default: () => [
        {
          title: '总数：',
          value: 'total'
        },
        {
          title: '待提交审核：',
          value: 'draftNum'
        },
        {
          title: '审核中：',
          value: 'submittedNum'
        },
        {
          title: '审核通过：',
          value: 'pastNum'
        },
        {
          title: '审核不通过：',
          value: 'rejectedNum'
        }
      ]
    },
    // api
    api: {
      type: Object,
      default: () => ({})
    },
    // 请求参数
    form: {
      type: Object,
      default: () => ({})
    },
    // 加载表格计数器
    loadCount: {
      type: [Number, String],
      default: () => 0
    }
  },
  computed: {
    // eslint-disable-next-line vue/return-in-computed-property
    columnsTotal() {
      let header = [
        {
          title: '分公司名称',
          dataIndex: 'branchCompanyName'
        },
        {
          title: '项目名称',
          dataIndex: 'projectName'
        }
      ]
      if (this.countTableType === 0)
        return [
          {
            title: '排名',
            width: 80,
            customRender() {
              return arguments[2] + 1
            }
          },
          header[0],
          ...this.columnsTotalTemp
        ]
      if (this.countTableType === 1)
        return [
          {
            title: '排名',
            width: 80,
            customRender() {
              return arguments[2] + 1
            }
          },
          header[0],
          header[1],
          ...this.columnsTotalTemp
        ]
    }
  },
  data() {
    return {
      sortType: undefined,
      countInfo: {}, // 汇总对象
      activeKey: [],
      expLoading:false,
      queryParam: {
        type: undefined
      },
      typeList: [
        { name: '根据总数量', key: '0' },
        { name: '根据科技奖数量', key: '1' },
        { name: '根据研发立项数量', key: '2' },
        { name: '根据工法数量', key: '3' },
        { name: '根据国家知识产权数量', key: '4' },
        { name: '根据论文数量', key: '5' },
        { name: '根据科技成果评价数量', key: '6' },
        { name: '根据科技查新数量', key: '7' }
      ],
      countTableType: 0,
      args: {},
      columnsTotalTemp: [
        { title: '获得总数量', dataIndex: 'gainTotalNum' },
        { title: '科技奖获得数量', dataIndex: 'technologyNum' },
        { title: '研发立项获得数量', dataIndex: 'contractNum' },
        { title: '工法获得数量', dataIndex: 'methodNum' },
        { title: '国家知识产权获得数量', dataIndex: 'propertyNum' },
        { title: '论文获得数量', dataIndex: 'paperNum' },
        { title: '科技成果评价获得数量', dataIndex: 'evaluateNum' },
        { title: '科技查新获得数量', dataIndex: 'noveltySearchNum' }
      ],
      loadDataSummary: async () => {
        let params = { rankingType: this.countTableType,rankingLogic:this.queryParam?.rankingLogic }
        if (this.queryParam.searchTime) {
          params.startTime = this.queryParam.searchTime[0]
          params.endTime = this.queryParam.searchTime[1]
        }
        let res = await this.api?.count(Object.assign(params, this.form))
        if (res.code === this.SUCCESS_CODE) {
          return { code: this.SUCCESS_CODE, data: res.data }
        } else {
          return { code: this.SUCCESS_CODE, data: [] }
        }
      }
    }
  },
  methods: {
    /**
     * 导出科技管理计划统计 
     * @param parameter
     */
     async achievementsLedgerExportFc(){
      this.expLoading = true;
      setTimeout(() => {
        this.expLoading = false;
      }, 3000);
      let params = { rankingType: this.countTableType,rankingLogic:this.queryParam?.rankingLogic }
        if (this.queryParam.searchTime) {
          params.startTime = this.queryParam.searchTime[0]
          params.endTime = this.queryParam.searchTime[1]
        }
        // let expqueryParam = Object.assign({}, params,this.$parent.$parent.$parent.$parent.$refs.searchArr.form.getFieldsValue());
        let res = await achievementsLedgerExport(params)
        this.handleDownload(res)
        this.expLoading = false;
    },
    /**
     * 转义下载
     * @param parameter
     */
     handleDownload(res){ 
      const blob = new Blob([res])
      // const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const filename = '科技成果台账.xls'
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      // downloadElement.download = filename // 获取文件名
      downloadElement.download = '科技成果排名.xls'// 获取文件名
      // downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    refresh() {
      let index = this.typeList.findIndex((v) => v.key === this.queryParam.rankingLogic)
      console.log('indexindexindexindex',index)
      if (index !== -1) {
        let ths = document.querySelectorAll('.summary-table th')
        ths.forEach((v) => {
          v.classList.remove('blue')
        })
        ths[(this.countTableType ? 3 : 2) + index].className = 'blue'
      }
      
      this.$refs.tableSummary?.getData(null, true)
    },
    search() {
      this.$refs.tableSummary?.getData(null, true)
    },
    // 切换汇总信息
    switchSummary(e) {
      this.countTableType = e
      this.$refs.tableSummary.getData(null, true)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-table-small > .ant-table-content > .ant-table-body > table > .ant-table-thead > tr > .blue {
  background: rgb(2, 167, 240) !important;;
  color: white !important;
}
</style>
